package com.nondo.rdp.stock.service.impl;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.stock.domain.SimulateAccount;
import com.nondo.rdp.stock.repository.SimulateAccountRepository;
import com.nondo.rdp.stock.service.SimulateAccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class SimulateAccountServiceImpl implements SimulateAccountService {
    @Autowired
    SimulateAccountRepository simulateAccountRepository;

    @Override
    public SimulateAccount findOne(Long id) {
        return this.simulateAccountRepository.findOne(id);
    }

    @Override
    public SimulateAccount save(SimulateAccount simulateAccount) {
        return this.simulateAccountRepository.save(simulateAccount);
    }

    @Override
    public void update(SimulateAccount simulateAccount) {
        this.simulateAccountRepository.save(simulateAccount);
    }

    @Override
    public void delete(Long id) {
        this.simulateAccountRepository.deleteById(id);
    }

    @Override
    public SimulateAccount findByUser(User user) {
        return this.simulateAccountRepository.findByUser(user);
    }

    @Override
    public Page<SimulateAccount> findAll(Page<SimulateAccount> page, SimulateAccount simulateAccount) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<SimulateAccount> dictPage = simulateAccountRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            //搜索ID
            if (simulateAccount.getId() != null && simulateAccount.getId() != 0) {
                predicates.add(builder.equal(root.get("id"), simulateAccount.getId()));
            }
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<SimulateAccount>(dictPage);
    }
}